<template>
  <div class="home">
    <ul>
      <li 
       v-for="item of dataList"
       :key="item.id"
      >
        <p>
          <span>{{ item.user }}</span>
          <span>{{ new Date(item.id) }}</span>
        </p>
        <p>{{ item.msg }}</p>
      </li>
    </ul>

    <input type="text" name="" id="" v-model="msg">
    <button @click="handleSendClick">发送</button>
  </div>
</template>

<script>

const ws = new WebSocket('ws://localhost:8000');

export default {
  name: 'Home',
  data() {
    return {
      dataList: [],
      user: '',
      msg: ''
    }
  },
  mounted() {

    this.user = localStorage.getItem('username');
    if(!this.user) {
      this.$router.push('/login');
      return;
    }
    console.log(this.user);
    
    ws.addEventListener('open', this.handleWsOpen.bind(this), false);
    ws.addEventListener('close', this.handleWsClose.bind(this), false);
    ws.addEventListener('error', this.handleWsError.bind(this), false);
    ws.addEventListener('message', this.handleWsMessage.bind(this), false);
  },
  methods: {
    handleSendClick() {

      ws.send(JSON.stringify({
        user: this.user,
        id: new Date().getTime(),
        msg: this.msg
      }))

      this.msg = ''
    },
    handleWsOpen(e) {
      console.log('websocket open', e);
    },
    handleWsClose(e) {
      console.log('websocket close', e);

    },
    handleWsError(e) {
      console.log('websocket error', e);

    },
    handleWsMessage(e) {
      console.log('websocket message', e.data);
      const msg = JSON.parse(e.data)
      console.log(msg);
      this.dataList.push(msg);
    },
  }
}
</script>
